package crazymakercircle;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: DRevelation
 * @Date: 2021/7/13 14:20
 */
@Slf4j
public class Plus2Test {

    private static final int MAX_TREAD = 10;
    private static final int MAX_TURN = 10000;

    @Test
    public void testSafePlus() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(MAX_TREAD);

        SafePlus safePlus = new SafePlus();

        for (int i = 0; i < MAX_TREAD; i++) {
            new Thread(() -> {
                for (int j = 0; j < MAX_TURN; j++) {
                    safePlus.increment();
                }
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();
        log.info("理论结果：" + MAX_TURN * MAX_TREAD);
        log.info("实际结果：" + safePlus.getCount());
        log.info("差距是：" + (MAX_TURN * MAX_TREAD - safePlus.getCount()));
    }


    class SafePlus {

        private AtomicInteger atomicInteger = new AtomicInteger();

        public void increment() {
            atomicInteger.incrementAndGet();
        }

        public int getCount() {
            return atomicInteger.get();
        }
    }
}
